package com.scisoft.scan.control.stock;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.nlscan.android.scan.ScanManager;
import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.CommonAdapter;
import com.scisoft.scan.control.CommonViewHolder;
import com.scisoft.scan.control.ScanHelper;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.PartBean;
import com.scisoft.scan.data.ShelvesBean;
import com.scisoft.scan.data.depot.WarehouseBean;
import com.scisoft.scan.data.QueryPageBean;
import com.scisoft.scan.data.shelves.ShelvesInfoBean;
import com.scisoft.scan.data.stock.StockFlowQueryBean;
import com.scisoft.scan.data.stock.StockInfoCheckBean;
import com.scisoft.scan.data.stock.StockInfoMoveBean;
import com.scisoft.scan.data.stock.StockInfoPositionBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.control.MainMenuActivity;
import com.scisoft.scan.data.stock.StockFlowBean;
import com.scisoft.scan.data.stock.StockInfoBean;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.SysParameter;
import com.scisoft.scan.ws.WebServiceHelper;
import com.scisoft.scan.ws.WebServiceHelper_Depot;
import com.scisoft.scan.ws.WebServiceHelper_Shelves;
import com.scisoft.scan.ws.WebServiceHelper_Stock;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.scisoft.scan.control.CommonAdapter.LOADING_END;
import static com.scisoft.scan.control.CommonAdapter.LOADING_MORE;
import static com.scisoft.scan.control.CommonAdapter.PULLUP_LOAD_MORE;

public class StockActivity extends Activity {
    private ImageView iv_Back; //返回按钮
    private ImageView iv_query; //搜索按钮
    private ClearEditText et_bar;//搜索框
    private EditText et_position;//货架
    private EditText et_MovePosition;//货架
    private List<String> depotList = new ArrayList<>();
    private List<WarehouseBean> depotBeanList = new ArrayList<WarehouseBean>();
    private int selectedDepotNo = 0;
    private boolean depotHasInited = false;
    //分页配置表
    private QueryPageBean pageBean = null;
    private int currentPage = 0;
    //分页显示控件
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private StockAdapter stockAdapter;
    private LinearLayoutManager mLayoutManager;
    private int lastVisibleItem; //最后一个可见Item的位置，关键所在
    float lastY = 0;
    private int scanFlag = 0;//货架扫码标识
    private int scanMoveFlag = 0;//移库扫码标识


    @Override
    @SuppressLint("ClickableViewAccessibility")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_stock);
        //初始化扫码
        init();
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(StockActivity.this, MainMenuActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
                finish();
            }
        });
        et_bar = findViewById(R.id.et_bar);
        //搜索框
        iv_query = findViewById(R.id.iv_query);
        iv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QueryData(true);
            }
        });
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int fullWidth = displayMetrics.widthPixels;


        mRefreshLayout = findViewById(R.id.swipe_layout);
        //mRefreshLayout.setEnabled(false);
        mRefreshLayout.setProgressViewEndTarget(true, 0);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mRefreshLayout.setRefreshing(false);
                QueryData(true);
            }
        });
        mRecyclerView = findViewById(R.id.lv_data);
        stockAdapter = new StockAdapter(StockActivity.this);
        stockAdapter.setItemLayout(R.layout.item_stock, R.id.hsv, R.id.layout_show, R.id.layout_hide, fullWidth);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        stockAdapter.setOnItemClickListener(new StockAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                StockInfoBean stockInfoBean = stockAdapter.getItemData(position);
//                if (stockInfoBean != null)
//                    QueryFlowData(stockInfoBean);
            }
        });
        //滚动的时候清空左滑按钮
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (Math.abs(event.getY() - lastY) > 5)
                            stockAdapter.clearLeftMenuList();
                }
                return false;
            }
        });
        mRecyclerView.setAdapter(stockAdapter);
        //设置滑动监听
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //判断是否滑动到底
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == stockAdapter.getItemCount()) {
                    //滑动到底，需要改变状态为 上拉加载更多
                    stockAdapter.changeMoreStatus(LOADING_MORE);
                    QueryData(false);
                } else {
                    stockAdapter.changeMoreStatus(PULLUP_LOAD_MORE);
                }
            }

            //更新最后可见位置
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();

            }
        });
        QueryData(true);
    }

    //查询库存
    private void QueryData(boolean refresh) {
        CommonUtil.showPress(this);
        QueryTask queryTask = new QueryTask(StockActivity.this, refresh);
        queryTask.execute();
    }

    //绑定数据
    private void BindData(Context context, List<StockInfoBean> newData, boolean refresh) {
        //清空
        stockAdapter.clearLeftMenuList();
        //数据
        if (!refresh) {
            if (newData.size() > 0) {
                stockAdapter.addMoreItem(newData);
            } else {
                stockAdapter.changeMoreStatus(LOADING_END);
            }
        } else {
            if (newData.size() > 0) {
                stockAdapter.clearAddItem(newData);
            } else {
                stockAdapter.clearAddItem(newData);
                stockAdapter.changeMoreStatus(LOADING_END);
            }
        }
    }

    //查询库存服务
    class QueryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        boolean mrefresh = true;
        private List<StockInfoBean> newData = new ArrayList<>();

        QueryTask(Context context, boolean refresh) {
            super();
            mcontext = context;
            mrefresh = refresh;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                String condition = et_bar.getUpperText().toString();
                //初始化仓库
                if (!depotHasInited) {
                    depotBeanList = WebServiceHelper_Depot.DEPOT_01();
                    selectedDepotNo = 0;
                    depotHasInited = true;
                }
                //重新刷新
                if (mrefresh) {
                    pageBean = null;
                }
                //第一次程序时需要先查询分页信息
                if (pageBean == null) {
                    pageBean = WebServiceHelper_Stock.STOCK_05(condition);
                    currentPage = 0;
                }
                //翻页
                currentPage++;
                //判断是否全部显示，如果没有就查询下一页
                if (currentPage <= pageBean.pageCount) {
                    newData = WebServiceHelper_Stock.STOCK_01(condition, pageBean.pageSize, currentPage);
                }
                //超过最大页则返回
                if (currentPage > pageBean.pageCount) {
                    currentPage = pageBean.pageCount;
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext, newData, mrefresh);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }


    //以下为扫码相关
    //初始化
    private void init(){
        //初始化Profile
        ScanHelper.CreateProfile(this);
        //设置广播消息的接收器
        registerReceiver();
    }

    //查询条码服务
    class QueryBarCodeTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String barCode;
        private BarCodeBean barCodeBean = null;

        QueryBarCodeTask(Context context, String barCode) {
            super();
            mcontext = context;
            this.barCode = barCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                barCodeBean = WebServiceHelper.ParseBarCode(barCode);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                if (barCodeBean == null || barCodeBean.barType == BarCodeBean.BAR_UNKNOWN) {
                    Toast.makeText(StockActivity.this, "无效二维码：" + barCode, Toast.LENGTH_LONG).show();
                } else if (barCodeBean.barType == BarCodeBean.BAR_PART) {
                    if (scanFlag == 1 || scanMoveFlag == 1) {
                        Toast.makeText(StockActivity.this, "请扫描货架", Toast.LENGTH_LONG).show();
                    } else {
                        et_bar.setText(barCodeBean.partBean.partNo);
                        QueryData(true);
                    }
                } else if (barCodeBean.barType == BarCodeBean.BAR_SHELVES) {
                    if (scanFlag == 1 && scanMoveFlag == 0) {
                        ShelvesInfoBean shelvesBean = barCodeBean.shelvesBean;
                        et_position.setText(shelvesBean.shelvesName);
                    } else if (scanFlag == 0 && scanMoveFlag == 1) {
                        ShelvesInfoBean shelvesBean = barCodeBean.shelvesBean;
                        et_MovePosition.setText(shelvesBean.shelvesName);
                    }
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //扫码处理
    private void ScanData(String barCode) throws Exception {
        if (barCode != null && barCode.length() > 0) {
            CommonUtil.showPress(this);
            QueryBarCodeTask queryBarCodeTask = new QueryBarCodeTask(StockActivity.this, barCode);
            queryBarCodeTask.execute();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        //IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        //registerReceiver(mResultReceiver, intFilter);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScanHelper.ACTION_RESULT_NOTIFICATION);   // for notification result
        filter.addAction(ScanHelper.ACTION_RESULT);                // for error code result
        filter.addCategory(Intent.CATEGORY_DEFAULT);    // needed to get version info
        filter.addAction(ScanHelper.ACTION_SCAN_OUTPUT); // register to received broadcasts via DataWedge scanning
        registerReceiver(mResultReceiver, filter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if (action.equals(ScanHelper.ACTION_SCAN_OUTPUT)) {
                // 处理扫码结果
                try {
                    String decodedData = intent.getStringExtra("com.symbol.datawedge.data_string");
                    ScanData(decodedData);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(StockActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    //适配器相关功能
    class StockAdapter extends CommonAdapter<StockInfoBean> {
        //构造函数
        public StockAdapter(Context context) {
            super(context);
        }

        @Override
        public void convert(CommonViewHolder holder, final StockInfoBean stockInfoBean, int position) {
            TextView tv_partNo = holder.getView(R.id.tv_partNo);
            TextView tv_partName = holder.getView(R.id.tv_partName);
            TextView tv_supplierName = holder.getView(R.id.tv_supplierName);
            TextView tv_kcs = holder.getView(R.id.tv_kcs);
            TextView tv_kck = holder.getView(R.id.tv_kck);
            TextView tv_ck = holder.getView(R.id.tv_ck);
            TextView tv_kq = holder.getView(R.id.tv_kq);
            TextView tv_hj = holder.getView(R.id.tv_hj);
            ImageView iv_img = holder.getView(R.id.iv_img);
            //获取相应索引的ItemBean对象
            StockInfoBean bean = mList.get(position);
            //设置控件的对应属性值
            tv_partNo.setText(bean.partNo);
            tv_partName.setText(bean.partName);
            tv_supplierName.setText(bean.supplierName);
            tv_kcs.setText(String.valueOf(bean.stockCount));
            tv_kck.setText(String.valueOf(bean.canUseCount));
            tv_ck.setText(bean.depotName);
            tv_kq.setText(bean.areaName);
            tv_hj.setText(bean.position);
            if (bean.imgUrl != null && !bean.imgUrl.equals("")) {
                Picasso.with(mContext).load(bean.imgUrl).into(iv_img);
            } else {
                iv_img.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_noimage));
            }
            //修改货架
            TextView tv_positiom = holder.getView(R.id.tv_positiom);
            tv_positiom.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alert_shelves(stockInfoBean);
                }
            });
            //盘点按钮
            TextView tv_check = holder.getView(R.id.tv_check);
            tv_check.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alert_check(stockInfoBean);
                }
            });
            //拍照
            TextView tv_takepohto = holder.getView(R.id.tv_takepohto);
            tv_takepohto.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    currentTakePicturePart = stockInfoBean;
                    if (isStoragePermissionGranted()) {
                        takePhoto();
                    }
                }
            });
            //编辑图片
            iv_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showpictures(stockInfoBean);
                }
            });
        }

        //弹出盘点窗口
        private void alert_check(final StockInfoBean stockInfoBean) {
            //1.创建一个Dialog对象,去除标题栏
            final Dialog mDialog = new Dialog(mContext);
            mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            //2.填充布局,将自定义布局设置进去
            LayoutInflater inflater = LayoutInflater.from(mContext);
            View dialogView = inflater.inflate(R.layout.dialog_partinfo_check, null);
            mDialog.setContentView(dialogView);
            //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            Window window = mDialog.getWindow();
            lp.copyFrom(window.getAttributes());
            lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
            mDialog.show();
            window.setAttributes(lp);
            //4、设置点击其它地方不让消失弹窗
            mDialog.setCancelable(false);
            //5、初始化控件
            //下拉列表
            TextView tv_zmshow = dialogView.findViewById(R.id.tv_zmshow);
            tv_zmshow.setText("账面 (" + stockInfoBean.depotName + " " +stockInfoBean.areaName + " " + stockInfoBean.position + ")");//账面 (J仓 J62/63/56)
            TextView tv_kycount = dialogView.findViewById(R.id.tv_kycount);
            tv_kycount.setText(String.valueOf(stockInfoBean.canUseCount));
            TextView tv_kccount = dialogView.findViewById(R.id.tv_kccount);
            tv_kccount.setText(String.valueOf(stockInfoBean.stockCount));
            TextView tv_zy = dialogView.findViewById(R.id.tv_zy);//成本
            tv_zy.setText(String.valueOf(stockInfoBean.occupyCount));
            final EditText et_spcount = dialogView.findViewById(R.id.et_spcount);
            // final EditText et_price = dialogView.findViewById(R.id.et_price);
            //et_price.setText(String.valueOf(stockInfoBean.price));

            TextView tv_ok = dialogView.findViewById(R.id.tv_ok);
            tv_ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //按下确定键后的事件
                    StockInfoCheckBean stockInfoCheckBean = new StockInfoCheckBean();
                    stockInfoCheckBean.stockId = stockInfoBean.stockId;
                    stockInfoCheckBean.partId = stockInfoBean.partId;
                    stockInfoCheckBean.partNo = stockInfoBean.partNo;
                    stockInfoCheckBean.partCode = stockInfoBean.partCode;
                    stockInfoCheckBean.checkCount = et_spcount.getText().toString();
                    //stockInfoCheckBean.checkPrice = et_price.getText().toString();

                    CommonUtil.showPress(StockActivity.this);
                    CheckTask checkTask = new CheckTask(StockActivity.this, stockInfoCheckBean, et_bar.getUpperText().toString());
                    checkTask.execute();
                    clearLeftMenuList();
                    mDialog.dismiss();
                }
            });
            TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDialog.dismiss();
                }
            });
        }

        //弹出修改货架窗口
        private void alert_shelves(final StockInfoBean stockInfoBean) {
            //1.创建一个Dialog对象,去除标题栏
            final Dialog mDialog = new Dialog(mContext);
            scanFlag = 1;
            scanMoveFlag = 0;
            mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            //2.填充布局,将自定义布局设置进去
            LayoutInflater inflater = LayoutInflater.from(mContext);
            View dialogView = inflater.inflate(R.layout.dialog_partinfo_shelves, null);
            mDialog.setContentView(dialogView);
            //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            Window window = mDialog.getWindow();
            lp.copyFrom(window.getAttributes());
            lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
            mDialog.show();
            window.setAttributes(lp);
            //4、设置点击其它地方不让消失弹窗
            mDialog.setCancelable(false);
            //5、初始化控件
            //下拉列表
            TextView tv_depot = dialogView.findViewById(R.id.tv_depot);
            tv_depot.setText(stockInfoBean.depotName);
            TextView tv_position = dialogView.findViewById(R.id.tv_position);
            tv_position.setText(stockInfoBean.position);
            et_position = dialogView.findViewById(R.id.et_position);

            TextView tv_ok = dialogView.findViewById(R.id.tv_ok);
            tv_ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //按下确定键后的事件
                    StockInfoPositionBean stockInfoPositionBean = new StockInfoPositionBean();
                    stockInfoPositionBean.stockId = stockInfoBean.stockId;
                    stockInfoPositionBean.partId = stockInfoBean.partId;
                    stockInfoPositionBean.partName = stockInfoBean.partName;
                    stockInfoPositionBean.partCode = stockInfoBean.partCode;
                    stockInfoPositionBean.newPosition = et_position.getText().toString();

                    CommonUtil.showPress(StockActivity.this);
                    PositionTask positionTask = new PositionTask(StockActivity.this, stockInfoPositionBean, et_bar.getUpperText().toString());
                    positionTask.execute();
                    clearLeftMenuList();
                    scanFlag = 0;
                    mDialog.dismiss();
                }
            });
            TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    scanFlag = 0;
                    mDialog.dismiss();
                }
            });
        }

        //弹出图片编辑窗口
        private void showpictures(StockInfoBean stockInfoBean) {
            Intent intent = new Intent(StockActivity.this, StockPictureEditActivity.class);
            intent.putExtra("stockInfoBean", stockInfoBean);
            startActivityForResult(intent, REQUEST_IMAGE_EDIT);
        }

    }

    //盘点服务
    class CheckTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String data = "";
        private StockInfoCheckBean stockInfoCheckBean;
        private List<StockInfoBean> newData = new ArrayList<>();

        CheckTask(Context context, StockInfoCheckBean stockInfoCheckBean, String data) {
            super();
            mcontext = context;
            this.stockInfoCheckBean = stockInfoCheckBean;
            this.data = data;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_Stock.STOCK_07(stockInfoCheckBean);
                if (msg.contains("成功")) {
                    newData = ReQuery(data);
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                //数据
                if (newData.size() > 0) {
                    stockAdapter.clearAddItem(newData);
                } else {
                    stockAdapter.changeMoreStatus(LOADING_END);
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //修改货架服务
    class PositionTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String data = "";
        private StockInfoPositionBean stockInfoPositionBean;
        private List<StockInfoBean> newData = new ArrayList<>();

        PositionTask(Context context, StockInfoPositionBean stockInfoPositionBean, String data) {
            super();
            mcontext = context;
            this.stockInfoPositionBean = stockInfoPositionBean;
            this.data = data;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_Shelves.SHELVES_10(stockInfoPositionBean);
                if (msg.contains("成功")) {
                    newData = ReQuery(data);
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                //数据
                if (newData.size() > 0) {
                    stockAdapter.clearAddItem(newData);
                } else {
                    stockAdapter.changeMoreStatus(LOADING_END);
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    private final int REQUEST_IMAGE_CAPTURE = 1;
    private final int REQUEST_IMAGE_COMMIT = 2;
    private final int REQUEST_IMAGE_EDIT = 3;
    private StockInfoBean currentTakePicturePart;

    //弹出拍照窗口
    private String mFilePath;

    private void takePhoto() {
        try {
            String guid = String.valueOf(System.currentTimeMillis());
            // 获取SD卡路径
            mFilePath = Environment.getExternalStorageDirectory().getPath() + "/" + SysParameter.PictureDir;
            File dir = new File(mFilePath);
            if (!dir.exists()) {    //exists()判断文件是否存在，不存在则创建文件
                dir.mkdirs();
            }
            String[] content = dir.list();
            for (int i = content.length - 1; i >= 0; i--) {
                File temp = new File(mFilePath, content[i]);
                temp.delete();
            }
            // 保存图片的文件名
            mFilePath = mFilePath + "/" + guid + ".png";

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                takePhotoBiggerThan7(mFilePath);
            } else {
                // 指定拍照意图
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 加载路径图片路径
                Uri mUri = Uri.fromFile(new File(mFilePath));
                // 指定存储路径，这样就可以保存原图了
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);

                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                } else {
                    Toast.makeText(getApplicationContext(), "无法启动拍照功能", Toast.LENGTH_LONG).show();
                }
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "拍照失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void takePhotoBiggerThan7(String absolutePath) {
        Uri mCameraTempUri;
        try {
            ContentValues values = new ContentValues(1);
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
            values.put(MediaStore.Images.Media.DATA, absolutePath);
            mCameraTempUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            if (mCameraTempUri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraTempUri);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            }
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
            } else {
                Toast.makeText(getApplicationContext(), "无法启动拍照功能", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            final Context context = getApplicationContext();
            int readPermissionCheck = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.READ_EXTERNAL_STORAGE);
            int writePermissionCheck = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (readPermissionCheck == PackageManager.PERMISSION_GRANTED && writePermissionCheck == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        } else {
            //permission is automatically granted on sdk<23 upon installation
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            takePhoto();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
                //拍照结果的处理
                if (currentTakePicturePart == null) {
                    Toast.makeText(StockActivity.this, "当前配件信息为空", Toast.LENGTH_LONG).show();
                    return;
                }
                //弹出确认窗口
                Intent intent = new Intent(StockActivity.this, StockPictureActivity.class);
                intent.putExtra("data", mFilePath);
                intent.putExtra("stockInfoBean", currentTakePicturePart);
                startActivityForResult(intent, REQUEST_IMAGE_COMMIT);

            } else if (requestCode == REQUEST_IMAGE_COMMIT && resultCode == RESULT_OK) {
                //拍照数据上传结束
                Toast.makeText(StockActivity.this, "上传成功", Toast.LENGTH_LONG).show();
                QueryData(true);
            } else if (requestCode == REQUEST_IMAGE_EDIT) {
                QueryData(true);
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "上传照片失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }

    }

    //重新查询
    private List<StockInfoBean> ReQuery(String data) throws Exception {
        List<StockInfoBean> newData = new ArrayList<>();
        currentPage = 0;
        //第一次程序时需要先查询分页信息
        pageBean = WebServiceHelper_Stock.STOCK_05(data);
        //翻页
        currentPage++;
        //判断是否全部显示，如果没有就查询下一页
        if (currentPage <= pageBean.pageCount) {
            newData = WebServiceHelper_Stock.STOCK_01(data, pageBean.pageSize, currentPage);
        }
        //超过最大页则返回
        if (currentPage > pageBean.pageCount) {
            currentPage = pageBean.pageCount;
        }
        return newData;
    }

}
